package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.encoder.JwtEncoder;
import com.tarena.lbs.common.enums.PassportResultEnum;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.param.AdminLoginParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.vo.LoginVO;
import com.tarena.lbs.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    public LoginVO adminLogin(AdminLoginParam param) throws BusinessException {
        String password = param.getPassword();
        AdminPO adminPO = adminRepository.selectAdminByPhone(param.getPhone());
        if(adminPO != null) {
            String adminPassword = adminPO.getAccountPassword();
            if(password.equals(adminPassword)){
                String jwt = generateJwt(adminPO);
                LoginVO loginVO = new LoginVO();
                loginVO.setJwt(jwt);
                loginVO.setId(adminPO.getId());
                loginVO.setNickname(adminPO.getNickname());
                return loginVO;
            } else {
                throw new BusinessException(PassportResultEnum.USER_PASSWORD_ERROR);
            }
        } else {
            throw new BusinessException(PassportResultEnum.ADMIN_NONE_EXIST);
        }
    }

    private String generateJwt(AdminPO po) throws BusinessException {
        //在jwt中携带的用户信息 并不是adminPO 而是单独设计的一个 用户认证对象 UserPrinciple
        //原因是要和数据库表格解耦
        UserPrinciple userPrinciple = new UserPrinciple();
        userPrinciple.setId(po.getId());
        userPrinciple.setNickname(po.getNickname());
        //角色 在后台管理中 有2个角色 admin表格 type=0 平台 type=1 商家
        //在认证对象放的角色是一个枚举Role ADMIN SHOP USER
        userPrinciple.setRole(po.getAccountType()==0? Roles.ADMIN:Roles.SHOP);
        //jwtEncoder 生成jwt的工具类
        return jwtEncoder.generateToken(userPrinciple);
    }
}
